package com.hk.Mgr.web.controller.kyc;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.kyc.CardReq;
import com.hk.Mgr.web.message.kyc.CardRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.DateUtil;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Card;
import com.hk.commons.entity.Points;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.kyc.ICard;
import com.hk.service.kyc.IPoints;
import com.hk.service.sys.ISysUser;

@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/cardsCtrl")
public class CardCtrl extends BaseCtrl {

	@Autowired
	private ICard cardService;
	
	
	@Autowired
	private IPoints pointsService;

	@Autowired
	private ISysUser sysUserService;

	private Logger logger = LoggerFactory.getLogger(CardCtrl.class);

	@Autowired
	public YingmiApiUtils utils;

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> update(@RequestBody CardReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();
		Integer id = req.getId();

		logger.info("mgr/cardCtrl/update  id = " + id);
		Card card = cardService.findById(id);

		try {
			if (card == null) {
				resp.setMsg("参数不对：id is null！");
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				return resp;
			} else {
				ReqToModelHelper.copyReqValueToModel(req, card);
				card.setStartDate(req.getStartDate().getTime());
				card.setEndDate(req.getEndDate().getTime());
				card.setExpireDate(req.getExpireDate().getTime());
				cardService.update(card);
				resp.setResult(true);
				resp.setResultCode(StatusCode.SUCCESS.key());
			}
		} catch (Exception e) {
			logger.error("更新卡券失败");
			resp.setMsg("更新卡券失败，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 更改状态
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/updateTotalNum", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> updateStatus(@RequestBody CardReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();
		Integer id = req.getId();
		Integer newTotalNum = req.getTotalNum();
		logger.info("mgr/cardCtrl/updateTotalNum  id = " + id
				+ " new totalNum = " + newTotalNum);

		Card card = cardService.findById(id);

		try {
			if (card == null) {
				resp.setMsg("参数不对：id is null！");
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				return resp;
			} else {
				if (newTotalNum < card.getUsedNum()) {
					resp.setMsg("卡券总数目小于已用卡券数目， 更改失败！");
					resp.setResultCode(StatusCode.PARAM_ERROR.key());
					return resp;
				} else {
					card.setTotalNum(newTotalNum);
					cardService.update(card);

					resp.setResult(true);
					resp.setResultCode(StatusCode.SUCCESS.key());
				}
			}
		} catch (Exception e) {
			logger.error("更新卡券失败");
			resp.setMsg("更新卡券失败，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 获得所有活动
	 * 
	 * @author jeff
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<CardRes>> list(@RequestBody CardReq req) {
		ResponseBase<List<CardRes>> resp = new ResponseBase<List<CardRes>>();
		List<CardRes> cardReslist = new ArrayList<CardRes>();
		List<Card> cardlist = new ArrayList<Card>();

		HqlFilter hqlFilter = new HqlFilter();

		if (req.getType() != null) {
			hqlFilter.addEQFilter("type", req.getType());
		}

		if (StringHelper.isNotEmpty(req.getCardDesc())) {
			hqlFilter.addLKFilter("cardDesc", req.getCardDesc());
		}
		
		List<Card> cardTotalList = cardService.findByFilter(hqlFilter);
		
		hqlFilter.addSort("cts");
		
		
		
		cardlist = cardService.findByFilter(hqlFilter, req.getCurPage(),
				req.getPageSize());
		
		for(Card card :cardlist){
			
			CardRes cardRes = new CardRes();
			
			ReqToModelHelper.copyReqValueToModel(card, cardRes);
			cardRes.setStartDateStr(DateUtil.longToShortDate(card.getStartDate()));
			cardRes.setEndDateStr(DateUtil.longToShortDate(card.getEndDate()));
			cardRes.setExpireDateStr(DateUtil.longToShortDate(card.getExpireDate()));
			if(card.getPointsRuleId() != null){
				Points points = pointsService.findById(card.getPointsRuleId());
				if(points != null){
					cardRes.setPointsRuleDesc(points.getId() + " : " + points.getActDesc());
				}
			
			}
			cardReslist.add(cardRes);
		}

		resp.setResult(cardReslist);
		resp.setSize(cardTotalList.size());
		resp.setResultCode(StatusCode.SUCCESS.key());

		return resp;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> save(@RequestBody CardReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();
		Card card = new Card();
		try {
			ReqToModelHelper.copyReqValueToModel(req, card);
			card.setStartDate(req.getStartDate().getTime());
			card.setEndDate(req.getEndDate().getTime());
			card.setExpireDate(req.getExpireDate().getTime());
			cardService.add(card);
			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());

		} catch (Exception e) {
			logger.error("add new card failed");
			resp.setMsg("保存卡券失败，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}
}
